home *** CD-ROM | disk | FTP | other *** search
/ Over 1,000 Windows 95 Programs / Over 1000 Windows 95 Programs (Microforum) (Disc 1).iso / 0957 / gnugrep / gui / grep.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  1996-07-24  |  19.0 KB  |  717 lines

  1. /* grep.c - main driver file for grep.
  2.    Copyright (C) 1992 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written July 1992 by Mike Haertel.  
  19.  
  20. Modified for Windows interface Donald Munro 1996 */
  21.  
  22. #pragma warning(disable : 4018) //signed/unsigned mismatch
  23.  
  24. #define HAVE_WORKING_MMAP  // Undefine this to not use Win32 Memory Mapping
  25. #include "stdafx.h"
  26. //#include <windows.h>
  27. #include <errno.h>
  28. #include <stdio.h>
  29. #include <errno.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <memory.h>
  33. #include <sys/stat.h>
  34. #include <sys/types.h>
  35. #include <fcntl.h>
  36. #include <io.h>
  37. #ifndef _WIN32
  38. #include "getpagesize.h"
  39. #endif
  40.  
  41. #include "grep.h"
  42. #include "GrepView.h"
  43. #include "DirMatcher.h"
  44. #include "kwset.h"
  45.  
  46. #undef MAX
  47. #define MAX(A,B) ((A) > (B) ? (A) : (B))
  48.  
  49. typedef char * caddr_t;
  50.  
  51. extern int lastexact;
  52.  
  53. #define VOID void
  54.     
  55. /* Define flags declared in grep.h. */
  56. char *matcher;
  57. int match_icase;
  58. int match_words;
  59. int match_lines;
  60. int count_matches;
  61. int status;
  62. int list_files;
  63. int suppress_errors;
  64.  
  65. int initialized =FALSE;
  66.  
  67. GrepDisplayCallback g_GrepCallback;
  68. CDirMatcher *pdirmatchMatcher;
  69. CGrepView *g_pView =NULL;
  70.  
  71. /* Functions we'll use to search. */
  72. static void (*compile)(char *, size_t);
  73. static char *(*execute)(char *, size_t, char **);
  74.  
  75. void RegFree(); // In search.cpp
  76.  
  77. /* For error messages. */
  78. static char *prog;
  79. static int errseen;
  80.  
  81. extern kwset_t kwset;
  82.  
  83. #ifdef _WIN32
  84. HFILE hFile;
  85. OFSTRUCT ReOpenBuff;
  86. HANDLE hMapAddr;
  87. caddr_t pMappedAddress;
  88.  
  89. long getpagesize()
  90. //-----------------
  91. {    SYSTEM_INFO sysInfo;
  92.     GetSystemInfo(&sysInfo);
  93.     return sysInfo.dwPageSize;
  94. }
  95. #endif
  96.  
  97. /* Print a message and possibly an error string.  Remember
  98.    that something awful happened. */
  99. static void error(const char *mesg, int errnum =0)
  100. //-------------------------------------------------
  101. {    CString strErr;
  102.     if (errnum)                     
  103.         strErr.Format("%s: %s: (%d)", prog, mesg, errnum);
  104.     else
  105.         strErr.Format("%s: %s: (%d)", prog, mesg, GetLastError());
  106.     errseen = 1;
  107.     (*g_GrepCallback)(g_pView, strErr);
  108. }
  109.  
  110. extern "C"
  111.     {    BOOL CreatePrivateHeap();
  112.         BOOL DestroyPrivateHeap();
  113.         char *xmalloc(size_t size);
  114.         char *xrealloc(char *ptr, size_t size);
  115.         void xfree(char *ptr);
  116.         void fatal(char *szErr, int nErrNo);
  117.     }
  118.  
  119. #define malloc xmalloc
  120. #define realloc xrealloc
  121. #define valloc xmalloc
  122. #define free xfree
  123.  
  124. /* Hairy buffering mechanism for grep.  The intent is to keep
  125.    all reads aligned on a page boundary and multiples of the
  126.    page size. */
  127.  
  128. static char *buffer;        /* Base of buffer. */
  129. static size_t bufsalloc;    /* Allocated size of buffer save region. */
  130. static size_t bufalloc;        /* Total buffer size. */
  131. static int bufdesc;        /* File descriptor. */
  132. static char *bufbeg;        /* Beginning of user-visible stuff. */
  133. static char *buflim;        /* Limit of user-visible stuff. */
  134.  
  135. #if defined(HAVE_WORKING_MMAP) 
  136. static int bufmapped;        /* True for ordinary files. */
  137. static struct stat bufstat;    /* From fstat(). */
  138. static off_t bufoffset;        /* What read() normally remembers. */
  139. #endif
  140.  
  141. /* Reset the buffer for a new file.  Initialize
  142.    on the first time through. */
  143. void reset(int fd, CString strPath)
  144. //---------------------------------
  145. {    if (!initialized)
  146.         {    initialized = TRUE;
  147. #ifndef BUFSALLOC
  148.             bufsalloc = MAX(8192, getpagesize());
  149. #else
  150.             bufsalloc = BUFSALLOC;
  151. #endif
  152.             bufalloc = 5 * bufsalloc;
  153. /* The 1 byte of overflow is a kludge for dfaexec(), which
  154. inserts a sentinel newline at the end of the buffer
  155. being searched.  There's gotta be a better way... */
  156.             buffer = (char *) valloc(bufalloc + 1);
  157.             if (!buffer)
  158.                 fatal("memory exhausted", 0);
  159.             bufbeg = buffer;
  160.             buflim = buffer;
  161.         }
  162.     bufdesc = fd; 
  163. #if defined(HAVE_WORKING_MMAP)
  164. #ifdef _WIN32
  165. #define S_ISREG(mode)  ((mode&0XF000) == 0X8000)
  166. #endif
  167.     if ( (fstat(fd, &bufstat) < 0) || (!S_ISREG(bufstat.st_mode)) )
  168.         bufmapped = 0;
  169.     else
  170.         { bufmapped = 1;
  171.             bufoffset = lseek(fd, 0, 1);
  172.         }
  173. #ifdef _WIN32
  174.     if (pMappedAddress != NULL)
  175.         {    UnmapViewOfFile(pMappedAddress);
  176.             pMappedAddress = NULL;
  177.         }
  178.     if (hMapAddr != NULL)
  179.         {    CloseHandle(hMapAddr);
  180.             hMapAddr = NULL;
  181.         }
  182.     hMapAddr = CreateFileMapping((HANDLE)hFile, NULL, PAGE_READONLY,0,0,NULL);
  183.     if (hMapAddr != NULL)
  184.         pMappedAddress = (caddr_t)MapViewOfFile(hMapAddr,FILE_MAP_READ,0,0,0);
  185.     else
  186.         TRACE2("Error %d opening file %s for mapping\n",GetLastError(),strPath);
  187. #endif
  188. #endif
  189. }
  190.  
  191. /* Read new stuff into the buffer, saving the specified
  192.    amount of old stuff.  When we're done, 'bufbeg' points
  193.    to the beginning of the buffer contents, and 'buflim'
  194.    points just after the end.  Return count of new stuff. */
  195. static int fillbuf(size_t save)
  196. //-----------------------------
  197. {    char *nbuffer, *dp, *sp;
  198.     int cc;
  199. #if defined(HAVE_WORKING_MMAP)
  200.     caddr_t maddr;
  201. #ifdef _WIN32
  202.     size_t sizeCopy;
  203. #endif
  204. #endif
  205.     static int pagesize;
  206.  
  207.     if (pagesize == 0 && (pagesize = getpagesize()) == 0)
  208.         abort();
  209.  
  210.     if (save > bufsalloc)
  211.         {    while (save > bufsalloc)
  212.             bufsalloc *= 2;
  213.             bufalloc = 5 * bufsalloc;
  214.             nbuffer = (char *) valloc(bufalloc + 1);
  215.             if (!nbuffer)
  216.                 fatal("memory exhausted", 0);
  217.         }
  218.     else
  219.         nbuffer = buffer;
  220.  
  221.     sp = buflim - save;
  222.     dp = nbuffer + bufsalloc - save;
  223.     bufbeg = dp;
  224.     while (save--)
  225.         *dp++ = *sp++;
  226.  
  227. /* We may have allocated a new, larger buffer.  Since
  228. there is no portable vfree(), we just have to forget
  229. about the old one.  Sorry. */
  230.     buffer = nbuffer;
  231.  
  232. #if defined(HAVE_WORKING_MMAP)
  233. #ifdef _WIN32
  234.     if (hMapAddr != NULL && pMappedAddress != NULL)
  235.         {    sizeCopy = bufalloc - bufsalloc;
  236.             if ( ((long)(bufoffset + sizeCopy)) >= bufstat.st_size)
  237.                 sizeCopy = bufstat.st_size - bufoffset;
  238.             memcpy(buffer + bufsalloc,pMappedAddress + bufoffset, sizeCopy);
  239.             cc = sizeCopy;
  240.             bufoffset += cc;
  241.         }
  242. //else will do tryread below
  243. #else
  244.     if (bufmapped && bufoffset % pagesize == 0
  245.             && bufstat.st_size - bufoffset >= bufalloc - bufsalloc)
  246.         {    maddr = buffer + bufsalloc;
  247.             maddr = mmap(maddr, bufalloc - bufsalloc, PROT_READ | PROT_WRITE,
  248.                                         MAP_PRIVATE | MAP_FIXED, bufdesc, bufoffset);
  249.             if (maddr == (caddr_t) -1)
  250.                 {    strerror(errno));
  251.                     goto tryread;
  252.                 }
  253.  
  254. #if 0
  255. /* You might thing this (or MADV_WILLNEED) would help,
  256. but it doesn't, at least not on a Sun running 4.1.
  257. In fact, it actually slows us down about 30%! */
  258.             madvise(maddr, bufalloc - bufsalloc, MADV_SEQUENTIAL);
  259. #endif
  260.             cc = bufalloc - bufsalloc;
  261.             bufoffset += cc;
  262.         }
  263. #endif // _WIN32
  264. else
  265.     {
  266. tryread:
  267. /* We come here when we're not going to use mmap() any more.
  268. Note that we need to synchronize the file offset the
  269. first time through. */
  270.         if (bufmapped)
  271.             {    bufmapped = 0;
  272.                 lseek(bufdesc, bufoffset, 0);
  273.             }
  274.         cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  275.     }
  276. #else
  277.     cc = read(bufdesc, buffer + bufsalloc, bufalloc - bufsalloc);
  278. #endif
  279.     if (cc > 0)
  280.         buflim = buffer + bufsalloc + cc;
  281.     else
  282.         buflim = buffer + bufsalloc;
  283.     return cc;
  284. }
  285.  
  286. /* Flags controlling the style of output. */
  287. static int out_quiet;        /* Suppress all normal output. */
  288. static int out_invert;        /* Print nonmatching stuff. */
  289. static int out_file;        /* Print filenames. */
  290. static int out_line;        /* Print line numbers. */
  291. static int out_byte;        /* Print byte offsets. */
  292. static int out_before;        /* Lines of leading context. */
  293. static int out_after;        /* Lines of trailing context. */
  294.  
  295. /* Internal variables to keep track of byte count, context, etc. */
  296. static size_t totalcc;        /* Total character count before bufbeg. */
  297. static char *lastnl;        /* Pointer after last newline counted. */
  298. static char *lastout;        /* Pointer after last character output;
  299.                    NULL if no character has been output
  300.                    or if it's conceptually before bufbeg. */
  301. static size_t totalnl;        /* Total newline count before lastnl. */
  302. static int pending;        /* Pending lines of output. */
  303.  
  304. static void nlscan(char *lim)
  305. //---------------------------
  306. { char *beg;
  307.  
  308.   for (beg = lastnl; beg < lim; ++beg)
  309.     if (*beg == '\n')
  310.       ++totalnl;
  311.   lastnl = beg;
  312. }
  313.  
  314. static void prline(char *beg, char *lim, char sep, CString strPath ="", 
  315.                                      CString strLine ="")
  316. //---------------------------------------------------------------------
  317. { nlscan(beg);
  318.  
  319.     strLine.Format("%s%c%d%c", strPath, sep, ++totalnl, sep);
  320.     lastnl = lim;
  321.     //if (out_byte)
  322.         {    CString strByte;
  323.             strByte.Format("%lu%c", totalcc + (beg - bufbeg), sep);
  324.             strLine += strByte;
  325.         }
  326.     int i = strLine.GetLength();
  327.     char *pch = strLine.GetBuffer(strLine.GetLength()+(int)(lim - beg) + 10);
  328.     char *p;
  329.     for (p=beg; p<lim; p++)
  330.         pch[i++] = *p;
  331.     pch[i] = 0;
  332.     strLine.ReleaseBuffer();
  333.     (*g_GrepCallback)(g_pView, strLine);
  334.     lastout = lim;
  335. }
  336.  
  337. /* Print pending lines of trailing context prior to LIM. */
  338. static void prpending(char *lim, CString strPath ="")
  339. //-----------------------------------------------
  340. { char *nl;
  341.  
  342.     if (!lastout)
  343.         lastout = bufbeg;
  344.     while (pending > 0 && lastout < lim)
  345.         {    --pending;
  346.             if ((nl = (char *)memchr(lastout, '\n', lim - lastout)) != 0)
  347.                 ++nl;
  348.             else
  349.                 nl = lim;
  350.             prline(lastout, nl, '|',strPath); //-
  351.         }
  352. }
  353.  
  354. /* Print the lines between BEG and LIM.  Deal with context crap.
  355.    If NLINESP is non-null, store a count of lines between BEG and LIM. */
  356. static void prtext(char *beg, char *lim, int *nlinesp, CString strPath)
  357. //---------------------------------------------------------------------
  358. {    static int used;        /* avoid printing "--" before any output */
  359.     char *bp, *p, *nl;
  360.     int i, n;
  361.  
  362.     if (!out_quiet && pending > 0)
  363.         prpending(beg, strPath);
  364.  
  365.     p = beg;
  366.  
  367.     if (!out_quiet)
  368.         {    /* Deal with leading context crap. */
  369.             CString strLine ="";
  370.             bp = lastout ? lastout : bufbeg;
  371.             for (i = 0; i < out_before; ++i)
  372.                 if (p > bp)
  373.                     do
  374.                         --p;
  375.                     while (p > bp && p[-1] != '\n');
  376.  
  377.             /* We only print the "--" separator if our output is
  378.                 discontiguous from the last output in the file. */
  379.             if ((out_before || out_after) && used && p != lastout)
  380.                 strLine = "--";
  381.  
  382.             while (p < beg)
  383.                 {    nl = (char *)memchr(p, '\n', beg - p);
  384.                     prline(p, nl + 1, '|',strPath,strLine); //-
  385.                     p = nl + 1;
  386.                 }
  387.         }
  388.  
  389.     if (nlinesp)
  390.         {
  391.     /* Caller wants a line count. */
  392.             for (n = 0; p < lim; ++n)
  393.                 {    if ((nl = (char *)memchr(p, '\n', lim - p)) != 0)
  394.                         ++nl;
  395.                     else
  396.                         nl = lim;
  397.                     if (!out_quiet)
  398.                         prline(p, nl, '|',strPath);
  399.                     p = nl;
  400.                 }
  401.             *nlinesp = n;
  402.         }
  403.     else
  404.         if (!out_quiet)
  405.             prline(beg, lim, '|',strPath);
  406.  
  407.     pending = out_after;
  408.     used = 1;
  409. }
  410.  
  411. /* Scan the specified portion of the buffer, matching lines (or
  412.    between matching lines if OUT_INVERT is true).  Return a count of
  413.    lines printed. */
  414. static int grepbuf(char *beg, char *lim, CString strPath)
  415. //-------------------------------------------------------
  416. {    int nlines, n;
  417.     register char *p, *b;
  418.     char *endp;
  419.  
  420.     nlines = 0;
  421.     p = beg;
  422.     while ((b = (*execute)(p, lim - p, &endp)) != 0)
  423.         {
  424.             /* Avoid matching the empty line at the end of the buffer. */
  425.             if (b == lim && ((b > beg && b[-1] == '\n') || b == beg))
  426.                 break;
  427.             if (!out_invert)
  428.                 {    prtext(b, endp, (int *) 0, strPath);
  429.                     nlines += 1;
  430.                 }
  431.             else 
  432.                 if (p < b)
  433.                     {    prtext(p, b, &n, strPath);
  434.                         nlines += n;
  435.                     }
  436.             p = endp;
  437.         }
  438.     if (out_invert && p < lim)
  439.         {    prtext(p, lim, &n, strPath);
  440.             nlines += n;
  441.         }
  442.     return nlines;
  443. }
  444.  
  445. /* Search a given file.  Return a count of lines printed. */
  446. static int grep(int fd, CString strPath)
  447. //--------------------------------------
  448. {    int nlines, i;
  449.     size_t residue, save;
  450.     char *beg, *lim;
  451.  
  452.     reset(fd, strPath);
  453.  
  454.     totalcc = 0;
  455.     lastout = 0;
  456.     totalnl = 0;
  457.     pending = 0;
  458.  
  459.     nlines = 0;
  460.     residue = 0;
  461.     save = 0;
  462.  
  463.     for (;;)
  464.         {    if (fillbuf(save) < 0)
  465.                 {    error(strPath, errno);
  466.                     return nlines;
  467.                 }
  468.             lastnl = bufbeg;
  469.             if (lastout)
  470.                 lastout = bufbeg;
  471.             if (buflim - bufbeg == save)
  472.                 break;
  473.             beg = bufbeg + save - residue;
  474.             for (lim = buflim; lim > beg && lim[-1] != '\n'; --lim)
  475.                 ;
  476.             residue = buflim - lim;
  477.             if (beg < lim)
  478.                 {    nlines += grepbuf(beg, lim, strPath);
  479.                     if (pending)
  480.                         prpending(lim, strPath);
  481.                 }
  482.             i = 0;
  483.             beg = lim;
  484.             while (i < out_before && beg > bufbeg && beg != lastout)
  485.                 {    ++i;
  486.                     do
  487.                         --beg;
  488.                     while (beg > bufbeg && beg[-1] != '\n');
  489.                 }
  490.             if (beg != lastout)
  491.                 lastout = 0;
  492.             save = residue + lim - beg;
  493.             totalcc += buflim - bufbeg - save;
  494.             //if (out_line)
  495.             nlscan(beg);
  496.         }
  497.     if (residue)
  498.         {    nlines += grepbuf(bufbeg + save - residue, buflim, strPath);
  499.             if (pending)
  500.                 prpending(buflim, strPath);
  501.         }
  502.     return nlines;
  503. }
  504.  
  505.  
  506. /* Go through the matchers vector and look for the specified matcher.
  507.    If we find it, install it in compile and execute, and return 1.  */
  508. int    setmatcher(char *name)
  509. //------------------------
  510. {    int i;
  511.  
  512.     for (i = 0; matchers[i].name; ++i)
  513.         if (strcmp(name, matchers[i].name) == 0)
  514.             {    compile = matchers[i].compile;
  515.                 execute = matchers[i].execute;
  516.                 return 1;
  517.             }
  518.     return 0;
  519. }  
  520.  
  521. int Grep(CGrepView *pView, GrepDisplayCallback GrepCallback)
  522. //----------------------------------------------------------
  523. { char *keys;
  524.     size_t keycc;
  525.     int keyfound, no_filenames;
  526.     
  527.     // Added by D Munro.  There seem to be lots of memory leaks somewhere in the C
  528.     // code so we create a Private heap to allocate from and then destroy it
  529.     // when finished.  All the code allocating and using the heap is in regex.c
  530.     // malloc, realloc and free are #defined to use xmalloc etc in all the C files.
  531.     if (! CreatePrivateHeap())
  532.         { AfxMessageBox("ERROR : Alocating Heap");
  533.             return FALSE;
  534.         }
  535.     g_GrepCallback = GrepCallback;
  536.     g_pView = pView;
  537.     pMappedAddress = NULL;
  538.     hMapAddr = NULL;
  539.     hFile = 0;
  540.  
  541.     keys = NULL;
  542.     keycc = 0;
  543.     keyfound = 0;
  544.     count_matches = 0;
  545.     no_filenames = 0;
  546.     list_files = 0;
  547.     suppress_errors = 0;
  548.     matcher = NULL;
  549.     initialized = FALSE; //Added DM
  550.     lastexact = 0;  // Added DM
  551.  
  552.     out_after = atoi(pView->m_strLinesAfter);
  553.     out_before = atoi(pView->m_strLinesBefore);
  554.     if (pView->m_strGrep == "GNU E-Grep")
  555.         matcher = "grep";
  556.     else
  557.         if (pView->m_strGrep == "POSIX E-Grep")
  558.             matcher = "posix-egrep";
  559.         else
  560.             matcher = "fgrep";        
  561.     TRACE1("Matcher = %s\n",matcher);
  562.     out_byte = pView->m_bOutputByte;
  563.     if (pView->m_bCountMatchesOnly)
  564.         {    out_quiet = 1;
  565.             count_matches = 1;
  566.         }
  567.     match_icase = (! pView->m_bMatchCase);
  568.     if (pView->m_bNamesOnly)
  569.         {    out_quiet = 1;
  570.             list_files = 1;
  571.         }
  572.     if (pView->m_bNoMatchFiles)
  573.         {    out_quiet = 1;
  574.             list_files = -1;
  575.         }
  576.     suppress_errors = pView->m_bSuppressErrors;
  577.     out_invert = pView->m_bNonMatching;
  578.     match_words = pView->m_bMatchWord;
  579.   match_lines = pView->m_bMatchLine;
  580.  
  581.     // Remove all \r for FGREP 
  582.     CString strPattern;
  583.     strPattern = "";
  584.     if (strcmp(matcher,"fgrep") == 0)    
  585.         for (int i=0; i<pView->m_strPattern.GetLength(); i++)
  586.             if (pView->m_strPattern[i] != '\r')
  587.                 strPattern += pView->m_strPattern[i];
  588.             else;
  589.     else
  590.         for (int i=0; i<pView->m_strPattern.GetLength(); i++)
  591.             if ( (pView->m_strPattern[i] == '\r') || (pView->m_strPattern[i] == '\n') )
  592.                 break;
  593.             else
  594.                 strPattern += pView->m_strPattern[i];
  595.             
  596.  
  597.     keys = (char *) ((const char *) strPattern);
  598.     keycc = strlen(keys);
  599.  
  600.   if (!setmatcher(matcher) && !setmatcher("default"))
  601.         abort();
  602.     
  603.     (*compile)(keys, keycc);
  604.  
  605.     status = 1;
  606.     
  607.     pdirmatchMatcher = new CDirMatcher(pView->m_strSpecs, TRUE, TRUE, TRUE, FALSE,
  608.                                                                             TRUE,TRUE);
  609.     if (pdirmatchMatcher->GetNoSpecs() <= 0)
  610.         {    AfxMessageBox("Grep ERROR : Error in Search Specifications");
  611.             pView->m_bGrepping = FALSE;
  612.             pView->m_buttonStart.SetWindowText("Start");
  613.             pView->m_comboSpecs.SetFocus();
  614.             delete pdirmatchMatcher;
  615.             DestroyPrivateHeap();
  616.             return -1;
  617.         }
  618.     pView->m_bStopGrep = FALSE;
  619.     pView->m_bGrepping = TRUE;
  620.     CString strDir;
  621.     for (int nDirIndex=0; nDirIndex<pView->m_listDirectories.GetCount(); nDirIndex++)
  622.         {    pView->m_listDirectories.GetText(nDirIndex,strDir);
  623.             DoGrep(strDir, pView, GrepCallback);
  624.         }
  625.     delete pdirmatchMatcher;
  626.  
  627.     // DM 19/07/1996
  628.     if (kwset != NULL)
  629.         { kwsfree(kwset);
  630.             kwset = NULL;
  631.         }
  632.  
  633.     DestroyPrivateHeap();
  634.     return(errseen ? 2 : status);
  635. }
  636.  
  637. void DoGrep(CString strDir, CGrepView *pView, GrepDisplayCallback GrepCallback)
  638. //-----------------------------------------------------------------------------
  639. {    strDir.TrimLeft(); strDir.TrimRight();
  640.     SetCurrentDirectory(strDir);
  641.     WIN32_FIND_DATA DirData;
  642.     int desc;
  643.     
  644.     MSG msg;
  645.     while (PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
  646.      DispatchMessage(&msg);
  647.     if (pView->m_bStopGrep) return;
  648.  
  649.     HANDLE hSearchDir = FindFirstFile("*.*",&DirData);
  650.     if (hSearchDir == INVALID_HANDLE_VALUE)
  651.         return;
  652.     CString strPath;
  653.  
  654.     while (1)
  655.         {    while (PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
  656.                 DispatchMessage(&msg);
  657.             if (    (strcmp(DirData.cFileName,".") == 0) || 
  658.                         (strcmp(DirData.cFileName,"..") == 0) )
  659.                 if (FindNextFile(hSearchDir, &DirData))
  660.                     continue;
  661.                 else
  662.                     {    FindClose(hSearchDir);
  663.                         break;
  664.                     }
  665.             if (pView->m_bStopGrep) return;
  666.             if (strDir.Right(1) == "\\") // Take care of root
  667.                 strPath.Format("%s%s",strDir,DirData.cFileName);
  668.             else
  669.                 strPath.Format("%s\\%s",strDir,DirData.cFileName);
  670.             if (DirData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
  671.                 if (pView->m_bRecurseDirectories)
  672.                     if (! pView->m_bStopGrep)
  673.                         {    DoGrep(strPath, pView, GrepCallback);
  674.                             SetCurrentDirectory(strDir);
  675.                         }
  676.                     else;
  677.                 else;
  678.             else
  679.                 {    if (pView->m_bStopGrep) return;
  680.                     if (pdirmatchMatcher->Match(&DirData))
  681.                         {    desc = _open(strPath, _O_RDONLY);
  682.                             if (desc < 0)
  683.                                 {    if (!suppress_errors)
  684.                                         error(strPath, errno);
  685.                                 }
  686.                             else
  687.                                 {    int count = grep(desc, strPath);
  688.                                     CString strMatches;
  689.                                     if (count_matches)
  690.                                         {    strMatches.Format("%s:%d", strPath,count);
  691.                                             (*GrepCallback)(g_pView, strMatches);
  692.                                         }
  693.                                     if (count)
  694.                                         {    status = 0;
  695.                                             if (list_files == 1)
  696.                                                 {    strMatches.Format("%s", strPath);
  697.                                                     (*GrepCallback)(g_pView, strMatches);
  698.                                                 }
  699.                                         }
  700.                                     else 
  701.                                         if (list_files == -1)
  702.                                             {    strMatches.Format("%s", strPath);
  703.                                                 (*GrepCallback)(g_pView, strMatches);
  704.                                             }
  705.                                 }
  706.                             if (desc != 0)
  707.                                 _close(desc);                                    
  708.                         }
  709.                 }
  710.             if (! FindNextFile(hSearchDir, &DirData))
  711.                 {    FindClose(hSearchDir);
  712.                     break;
  713.                 }
  714.         }
  715.     return;
  716. }
  717.